import 'package:OASys/components/MyLoading.dart';
import 'package:OASys/httpConfig/DioManager.dart';
import 'package:OASys/httpConfig/NWApi.dart';
import 'package:OASys/httpConfig/NWMethod.dart';
import 'package:OASys/route/myRoute.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class LoginPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: MyLoginPage(),
      ),
      onGenerateRoute: (RouteSettings settings) {
        return onGenerateRoute(settings);
      },
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyLoginPage extends StatefulWidget {
  @override
  _MyLoginPageState createState() => _MyLoginPageState();
}

class _MyLoginPageState extends State<MyLoginPage> {
  var username = "";
  var password = "";
  bool isShow = true;
  DateTime _lastQuitTime;

  @override
  void initState() {
    super.initState();
    clearPrefs();
  }

  void show() {
    setState(() {
      isShow = !isShow;
    });
  }

  Future<void> getToken() async {
    var prefs = await SharedPreferences.getInstance();
    print(prefs.getString('token'));
  }

  Future<void> clearPrefs() async {
    var prefs = await SharedPreferences.getInstance();
    prefs.clear();
  }

  Future<void> login() async {
    print("正在登录......");
    show();
    DioManager().request<String>(
      NWMethod.POST,
      NWApi.loginPath,
      params: {
        "username": username,
        "password": password,
      },
      success: (data) async {
        show();
        print("token : $data");
        var prefs = await SharedPreferences.getInstance();
        prefs.setString('token', data);
        Toast.show(
          '登录成功',
          context,
          gravity: Toast.CENTER,
          duration: 2,
        );
        Navigator.of(context).pop();
        Navigator.of(context).pushNamed('/home');
      },
      error: (error) {
        show();
        Toast.show(
          "登录失败，错误为${error.message}",
          context,
          gravity: Toast.CENTER,
          duration: 2,
        );
      },
    );
  }

  void usernameChange(value) {
    username = value;
  }

  void pwdChange(value) {
    password = value;
  }

  void toRegister() {
    print('toRegister');
    Navigator.of(context).pushNamed('/register');
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Stack(
        children: [
          Container(
            color: Color.fromRGBO(240, 240, 240, 1),
            padding: EdgeInsets.fromLTRB(100, 180, 100, 100),
            child: ListView(
              children: [
                Container(
                  padding: EdgeInsets.only(bottom: 50),
                  child: Center(
                    child: Text(
                      "OA System",
                      style: TextStyle(
                        fontSize: 25,
                        color: Colors.blue,
                      ),
                    ),
                  ),
                ),
                TextField(
                  decoration: InputDecoration(
                    hintText: '请输入用户名',
                    icon: Icon(Icons.person),
                  ),
                  onChanged: usernameChange,
                ),
                TextField(
                  decoration: InputDecoration(
                    hintText: '请输入密码',
                    icon: Icon(Icons.lock),
                  ),
                  obscureText: true,
                  onChanged: pwdChange,
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(0, 15, 5, 15),
                  alignment: Alignment.bottomRight,
                  child: Text.rich(
                    TextSpan(
                      children: [
                        TextSpan(
                            text: '还没有账号？', style: TextStyle(fontSize: 10)),
                        TextSpan(
                          text: '注册',
                          style: TextStyle(color: Colors.blue, fontSize: 10),
                          recognizer: TapGestureRecognizer()
                            ..onTap = toRegister,
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  child: RaisedButton(
                    onPressed: login,
                    child: Text("登  录"),
                    color: Colors.blue,
                    textColor: Colors.white,
                    disabledTextColor: Colors.red,
                  ),
                ),
              ],
            ),
          ),
          Offstage(
            offstage: isShow,
            child: MyLoading(
              loadingText: '登录中',
            ),
          ),
        ],
      ),
      onWillPop: () async {
        if (_lastQuitTime == null ||
            DateTime.now().difference(_lastQuitTime).inSeconds > 1) {
          print('再按一次 Back 按钮退出');
          Toast.show('再次返回退出app', context);
          _lastQuitTime = DateTime.now();
          return false;
        } else {
          print('退出');
          Navigator.of(context).pop();
          return true;
        }
      },
    );
  }
}
